package com.storydo.thread.pool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicLong;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Task extends Thread {

	@Setter
	private BlockingQueue<TaskResult> resultQueue;
	
	private AtomicLong num;
	
	private Argument arg;
	
	private Process process;
	
	private boolean stop = false;
	
	public Task(String name, Argument arg, AtomicLong num) {
		super(name);
		this.arg = arg;
		this.num = num;
	}
	
	public void kill() {
		this.stop = true;
		if (this.process != null) {
			process.destroy();
		}
	}
	
	@Override
	public void run() {
		while (true) {
			BufferedReader br = null;
			try {
				long current = num.getAndIncrement();
				if (current >= arg.getNMax().longValue()) {
					return;
				}
				if (arg.getProgram() == null) {
					log.error("program error ---");
					return;
				}
				this.process = Runtime.getRuntime().exec(String.format("%s " + current, arg.getProgram()));
				br = new BufferedReader(new InputStreamReader(process.getInputStream()));
				String line = null; StringBuilder sb = new StringBuilder();
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
				if (sb.length() <= 0 && stop) {
					return;
				}
				TaskResult result = new TaskResult(getName(), String.format("%d", current), sb.toString().trim());
				this.resultQueue.offer(result);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}finally {
				try {
					if (br != null) {
						br.close();
					}
				} catch (IOException e) {
				}
			}
		}
	}
	
}
